<template>
  <div class="video-player" @wheel="handleWheel">
    <div class="timeline-container">
      <div ref="timeTooltip" class="tooltip">
        {{ formatDay(chooesDay) }} {{ formatTime(currentTime) }}
      </div>
      <div class="box">
        <div v-for="(item, cindex) in videos" :key="cindex">
          <div
            v-if="item.deviceNum"
            style="margin-bottom: 4px; width: 98.6%; margin-left: 10px; margin-right: 18px"
          >
            <div style="color: white; font-size: 12px; height: 20px">{{ item.deviceNum }}</div>
            <div
              :style="{
                backgroundImage: item.backgroundImage
                  ? item.backgroundImage
                  : 'linear-gradient(to right, white 0%, white 100%)'
              }"
              style="height: 2px; transition: transform 0.3s ease-in-out"
            >
            </div>
          </div>
        </div>
        <input
          type="range"
          :min="mintime"
          :max="maxtime"
          v-model="currentTime"
          @input="seekVideo"
          class="timeline"
        />

        <div class="time-markers">
          <div
            v-for="(marker, index) in timeMarkers"
            :key="marker"
            class="time-marker"
            :style="{ left: `${(marker / time) * 100}%` }"
            @click="clickTime(marker)"
          >
            <span class="fg"></span>
            <span v-if="index % 2 == 0"> {{ formatTime(marker) }}</span>
            <span v-else class="test">{{}} </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElSlider } from 'element-plus'
import { ref, computed, onMounted, watch, defineEmits, watchEffect } from 'vue'
const props = defineProps({
  chooesTime: {
    type: Number,
    default: 0
  },
  chooesDay: {
    type: Date,
    default: ''
  },
  videos: {
    type: Array,
    default: () => []
  }
})
const mintime = ref(0)
const maxtime = ref(24 * 60 * 60 - 1)
const time = ref(24 * 60 * 60)
const currentTime = ref(0)
const timeTooltipVisible = ref(false)
const timeTooltip = ref(null)
const box = ref(null)
const show = ref(true)
watch(
  () => props.chooesTime,
  (chooesTime) => {
    currentTime.value = parseInt(chooesTime)
  },
  {
    deep: true,
    immediate: true
  }
)
// 定义时间轴缩放级别，初始为24小时状态
// const scaleLevel = ref(1) // 1表示24小时状态
// 修改缩放级别定义
const scaleLevel = ref(2) // 初始为24小时状态
const timeMarkers1 = ref([])
// 定义时间轴缩放的最大和最小级别
const maxScaleLevel = 4 // 最大24小时状态
const minScaleLevel = 1 // 最小1分钟状态
const return60Markers = () => {
  // 定义总秒数
  let totalSeconds = currentTime.value

  // 计算小时数和分钟数
  let hours = Math.floor(totalSeconds / 3600)
  let minutes = Math.floor((totalSeconds % 3600) / 60)

  // 计算一个小时后的数据
  let oneHourLater = totalSeconds + 3600 // 加上一个小时的秒数

  // 重新计算小时数和分钟数
  let hoursLater = Math.floor(oneHourLater / 3600)
  let minutesLater = Math.floor((oneHourLater % 3600) / 60)
  let intervalSeconds = (oneHourLater - totalSeconds) / 60 // 计算间隔分钟数
  let markers = []
  // let interval = time.value / (12 * scaleLevel.value) // 根据缩放级别调整间隔(48 * scaleLevel.value)
  for (let i = 0; i < 60; i++) {
    markers.push(totalSeconds + intervalSeconds * i)
  }
  markers.push(oneHourLater)
  mintime.value = totalSeconds

  // timeMarkers.value = markers
  console.log('----------------', markers)
  return markers
}
const clickTime = (time) => {
  currentTime.value = time
  console.log('-------clickTime---------', time)
  if (scaleLevel.value == 8) {
    props.videos?.map((video) => {
      setVideoRangeBackground(video)
    })
  } else {
    props.videos?.map((video) => {
      setVideoRangeBackground1(video)
    })
  }

  emits('currentTimeChange', currentTime.value)
}
const setVideoRangeBackground = (video) => {
  const gradientStops = ['white 0%']
  if (video.videos) {
    video.videos.forEach((interval) => {
      const startPercent = ((interval.startTime - currentTime.value) / 3600) * 100
      const endPercent = ((interval.endTime - currentTime.value) / 3600) * 100
      gradientStops.push(`white ${startPercent}%`)
      gradientStops.push(`red ${startPercent}%`)
      gradientStops.push(`red ${endPercent}%`)
      gradientStops.push(`white ${endPercent}%`)
    })
  }

  gradientStops.push('white 100%')
  video.backgroundImage = `linear-gradient(to right, ${gradientStops.join(', ')})`
}
const setVideoRangeBackground1 = (video) => {
  const gradientStops = ['white 0%']
  if (video.videos) {
    video.videos.forEach((interval) => {
      const startPercent = (interval.startTime / 86400) * 100
      const endPercent = (interval.endTime / 86400) * 100
      gradientStops.push(`white ${startPercent}%`)
      gradientStops.push(`red ${startPercent}%`)
      gradientStops.push(`red ${endPercent}%`)
      gradientStops.push(`white ${endPercent}%`)
    })
  }

  gradientStops.push('white 100%')
  video.backgroundImage = `linear-gradient(to right, ${gradientStops.join(', ')})`
}
watch(scaleLevel, (newVal, oldVal) => {
  if (newVal !== 8) {
    mintime.value = 0
    maxtime.value = 24 * 60 * 60 - 1
    props.videos?.map((video) => {
      setVideoRangeBackground1(video)
    })
  } else {
    maxtime.value = currentTime.value + 3600
    props.videos?.map((video) => {
      setVideoRangeBackground(video)
    })
  }
})
const timeMarkers = computed(() => {
  if (scaleLevel.value == 8) {
    return return60Markers()
  }

  const markers = []
  let interval = time.value / (12 * scaleLevel.value) // 根据缩放级别调整间隔(48 * scaleLevel.value)
  for (let i = 0; i < time.value - 1; i += interval) {
    markers.push(i)
  }
  markers.push(time.value - 1)
  return markers
})

onMounted(() => {})

const onTimeUpdate = (event) => {
  console.log('Time updated:', event.target.value)
  // currentTime.value = videoPlayer.value.currentTime;
}
const emits = defineEmits(['currentTimeChange'])
const seekVideo = () => {
  console.log('Seeking to:', currentTime.value)
  emits('currentTimeChange', currentTime.value)
  // videoPlayer.value.currentTime = currentTime.value;
}
// defineExpose({
//   gettime: () => currentTime.value,
//   seekVideo
// })

const formatDay = (date) => {
  const options = { year: 'numeric', month: '2-digit', day: '2-digit' }
  return new Intl.DateTimeFormat('zh-CN', options).format(date)
}
const formatTime = (seconds) => {
  const date = new Date(null)
  date.setSeconds(seconds)

  return date.toISOString().substr(11, 5)
}

const handleMouseMove = (event) => {
  const rect = event.target.getBoundingClientRect()
  const position = (event.clientX - rect.left) / rect.width
  const tooltipPosition = position * 100
  currentTime.value = position * time.value
  timeTooltipVisible.value = true

  if (timeTooltip.value) {
    timeTooltip.value.style.left = `${tooltipPosition}%`
    timeTooltip.value.style.transform = `translateX(-50%)`
  }
}
// 计算时间标记间隔
const calculateInterval = () => {
  if (scaleLevel.value === 1) {
    // 24小时状态，48等分
    return time.value / 48
  } else {
    // 最大缩放级别，以分钟计算，60等分
    return time.value / 24 / 60 // 1小时的秒数 24 time.value / /
  }
}
const handleWheel = (event) => {
  event.preventDefault()
  if (event.deltaY < 0) {
    console.log('向上滚动')
    if (scaleLevel.value < 5) {
      scaleLevel.value *= 2 // 每次放大，时间轴范围缩小一半
    }
    // } else {
    //   // 定义总秒数
    //   let totalSeconds = currentTime.value

    //   // 计算小时数和分钟数
    //   let hours = Math.floor(totalSeconds / 3600)
    //   let minutes = Math.floor((totalSeconds % 3600) / 60)

    //   // 计算一个小时后的数据
    //   let oneHourLater = totalSeconds + 3600 // 加上一个小时的秒数

    //   // 重新计算小时数和分钟数
    //   let hoursLater = Math.floor(oneHourLater / 3600)
    //   let minutesLater = Math.floor((oneHourLater % 3600) / 60)
    //   let intervalSeconds = (oneHourLater - totalSeconds) / 60 // 计算间隔分钟数
    //   let markers = []
    //   // let interval = time.value / (12 * scaleLevel.value) // 根据缩放级别调整间隔(48 * scaleLevel.value)
    //   for (let i = 0; i < 60; i++) {
    //     markers.push(totalSeconds + intervalSeconds * i)
    //   }
    //   markers.push(oneHourLater)
    //   // timeMarkers.value = markers
    //   console.log('----------------', markers)
    //   show.value = false
    //   timeMarkers1.value = markers
    // }
  } else {
    if (scaleLevel.value > 1) {
      scaleLevel.value /= 2 // 每次缩小，时间轴范围扩大一倍
    }
    console.log('向下滚动')
  }
  // console.log('----------------', scaleLevel.value, timeMarkers.value, currentTime.value)

  // 鼠标滚轮上滑，放大时间轴
  // if (event.deltaY < 0) {
  //   if (scaleLevel.value > minScaleLevel) {
  //     scaleLevel.value /= 2 // 每次放大，时间轴范围缩小一半
  //     mintime.value = 54000 //currentTime.value - calculateInterval() / 2
  //   }
  // } else {
  //   // 鼠标滚轮下滑，缩小时间轴
  //   if (scaleLevel.value < maxScaleLevel) {
  //     scaleLevel.value *= 2 // 每次缩小，时间轴范围扩大一倍
  //   }
  // }
  // // 根据新的缩放级别调整currentTime，保持当前播放点为中心
  // const currentMarkerIndex = timeMarkers.value.findIndex((marker) => marker <= currentTime.value)
  // const newInterval = calculateInterval()
  // const centerTime = timeMarkers.value[currentMarkerIndex] + newInterval / 2
  // currentTime.value = Math.min(Math.max(centerTime, 0), time.value)
}
</script>

<style scoped>
.video-player {
  overflow: hidden;
}
.timeline-container {
  padding: 10rpx 20px;
}
.timeline {
  /* position: absolute;
    bottom: 20px;
    left: 0; */
  z-index: 10;
  cursor: pointer;
  width: 98.6%;
  margin-left: 10px;
  margin-right: 18px;
  transition: transform 0.3s ease-in-out;
}

.time-markers {
  /* position: relative; */
  display: flex;
  justify-content: space-between;
  width: 100%;
  /* margin-top: 10px; */
  margin-top: -8px;
}
.time-markers1 {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.time-marker1 {
  color: white;
  width: 1px;
  height: 16px;
  background: #fff;
  white-space: nowrap;
  margin-left: 14px;
}
.time-marker {
  /* position: absolute;
    top: -10px; */
  color: white;
  transform: translateY(11%);
  font-size: 12px;
  white-space: nowrap;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  /* position: relative; */
  cursor: pointer;
}
.fg {
  width: 1px;
  height: 10px;
  background: #fff;
}
/* .time-marker::after {
    content: '';
    position: absolute;
    height: 3px;
    width: 1px;
    background-color: #fff;
  } */

.tooltip {
  /* position: absolute; */
  /* background: #555; */
  width: 100%;
  color: #fff;
  text-align: center;
  /* margin-bottom: -10px; */
  /* padding: 5px; */
  border-radius: 5px;
  /* bottom: 38px;
    left: 0; */
  white-space: nowrap;
  /* transform: translateX(-50%); */
}
.test {
  content: '  ';
  height: 10px;
  margin-top: 8px;
}
.test::after {
  content: '';
}
#range-container {
  position: relative;
  width: 98.6%;
  margin-left: 10px;
  margin-right: 18px;
  height: 2px;
}

#time-range {
  width: 100%;
  appearance: none;
  /* background: linear-gradient(to right, white, white); */
}

#time-range::-webkit-slider-thumb {
  appearance: none;
  width: 10px;
  height: 100%;
  background: black;
  cursor: pointer;
}

#time-range::before {
  content: '';
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  height: 100%;
  background: red;
  pointer-events: none;
}
</style>
